﻿Imports System.Xml
Imports System.IO
Imports System.Text
Imports System.Threading

Public Class frmMain
    Private Client As New TCDClient()
    Private _Thread As Thread

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
        Form.CheckForIllegalCrossThreadCalls = False
        txtMaLop.Focus()
        For i = Now.Year To Now.Year - 9 Step -1
            cbbNamHoc.Items.Add(String.Format("{0}-{1}", i, i + 1))
        Next
        cbbNamHoc.SelectedItem = My.Settings.NamHoc
        txtMaLop.AutoCompleteCustomSource.Clear()
        For Each Str As String In My.Settings.CsMaLop.Split("|")
            txtMaLop.AutoCompleteCustomSource.Add(Str)
        Next
    End Sub

    Private Sub frmMain_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        If _Thread IsNot Nothing Then
            If _Thread.IsAlive Then
                _Thread.Abort()
            End If
        End If
        Dim accs As New StringBuilder()
        For Each Str As String In txtMaLop.AutoCompleteCustomSource
            If accs.Length <> 0 Then accs.Append("|")
            accs.Append(Str)
        Next
        My.Settings.CsMaLop = accs.ToString()
        My.Settings.Save()
    End Sub

    Private Sub btnTraCuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTraCuu.Click
        btnXoa_Click(sender, e)
        txtMaLop.AutoCompleteCustomSource.Add(txtMaLop.Text)
        _Thread = New Thread(AddressOf TraCuu)
        _Thread.Start()
    End Sub

    Private Sub TraCuu()
        panCongCu.Enabled = False
        lvwKetQua.Enabled = False
        lvwKetQua.ClearSort()
        Try
            Dim raw As String = FindBetween(Client.Download(
                "http://203.162.246.116/tracuudiem/Default.aspx", 2,
                "__VIEWSTATE", "/wEPDwUKMTU3ODAwODk2Mg9kFgICAw9kFgQCAQ9kFgICBQ8QZA8WDGYCAQICAgMCBAIFAgYCBwIIAgkCCgILFgwQBQkyMDA4LTIwMDkFCTIwMDgtMjAwOWcQBQkyMDA5LTIwMTAFCTIwMDktMjAxMGcQBQkyMDEwLTIwM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gKEgaeuCwKFgYuMBAKcgYv/CALq1ffEBQLt1ffEBQLJ4vT1DdItl6p3XcEQJVY5xcBruq+nN+j9ZfKJwVxdiv5vgLkz",
                "txtThongTin", txtMaLop.Text,
                "ckbDiemToanKhoa", "",
                "ddlNamHoc", cbbNamHoc.SelectedItem,
                "HocKy", "radHocKy" & nudKy.Value,
                "btnTimKiem", "Tìm kiếm"
            ), "<table class='tblKetQua'>", "</table>")(0).Replace("</tr><td>", "</tr><tr><td>")

            Dim data As Byte() = Encoding.UTF8.GetBytes("<table class='tblKetQua'>" & raw & "</table>")
            Dim xd As New XmlDocument()
            Using ms As New MemoryStream(data)
                xd.Load(ms)
            End Using

            Dim nl As XmlNodeList = xd.GetElementsByTagName("tr")
            nl(0).ParentNode.RemoveChild(nl(0))

            For Each tr As XmlNode In nl
                Dim td As XmlNodeList = tr.SelectNodes("td")
                Dim li As ListViewItem = lvwKetQua.Items.Add(td(0).InnerText)
                li.SubItems.Add(td(1).InnerText)

                lblSinhVien.Text = td(1).InnerText
                LayDiemSV(li)
            Next

            MsgBox("Lấy bảng điểm hoàn tất !", MsgBoxStyle.Information)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Lỗi")
        Finally
            lblSinhVien.Text = "---"
            lblTrangThai.Text = "---"
            lvwKetQua.Enabled = True
            panCongCu.Enabled = True
        End Try
    End Sub

    Private Sub LayDiemSV(ByVal li As ListViewItem)
        For timeout As Integer = 0 To 4
            lblTrangThai.Text = "lấy dữ liệu"
            Dim raw As Object = FindBetween(Client.Download(
                "http://203.162.246.116/tracuudiem/Default.aspx", 2,
                "__VIEWSTATE", "/wEPDwUKMTU3ODAwODk2Mg9kFgICAw9kFgQCAQ9kFgICBQ8QZA8WDGYCAQICAgMCBAIFAgYCBwIIAgkCCgILFgwQBQkyMDA4LTIwMDkFCTIwMDgtMjAwOWcQBQkyMDA5LTIwMTAFCTIwMDktMjAxMGcQBQkyMDEwLTIwMTEFCTIwMTAtMjAxMWcQ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gYv/CALq1ffEBQLt1ffEBQLJ4vT1DdItl6p3XcEQJVY5xcBruq+nN+j9ZfKJwVxdiv5vgLkz",
                "txtThongTin", li.Text,
                "ckbDiemToanKhoa", "",
                "ddlNamHoc", cbbNamHoc.SelectedItem,
                "HocKy", "radHocKy" & nudKy.Value,
                "btnTimKiem", "Tìm kiếm"
            ), "<table class='tblKetQua'>", "</table>")
            lblTrangThai.Text = "lấy dữ liệu xong"

            If raw.Length = 0 Then
                lblTrangThai.Text = "Lỗi, thử lại lần " & (timeout + 1)
                Thread.Sleep(1000)
                Continue For
            Else
                raw = raw(0).Replace("</tr><td>", "</tr><tr><td>")
            End If

            Dim data As Byte() = Encoding.UTF8.GetBytes("<table class='tblKetQua'>" & raw & "</table>")
            Dim xd As New XmlDocument()
            Using ms As New MemoryStream(data)
                xd.Load(ms)
            End Using

            Dim nl As XmlNodeList = xd.GetElementsByTagName("tr")
            nl(0).ParentNode.RemoveChild(nl(0))

            For Each tr As XmlNode In nl
                Dim td As XmlNodeList = tr.SelectNodes("td")
                If tr.Equals(nl(nl.Count - 1)) Then
                    li.SubItems(2).Text = td(0).SelectNodes("b")(0).InnerText
                Else
                    If Not lvwKetQua.Columns.ContainsKey(td(0).InnerText) Then
                        lblTrangThai.Text = "thêm môn học " & td(1).InnerText
                        lvwKetQua.Columns.Add(td(0).InnerText, td(1).InnerText).Tag = "Number"
                    End If
                    For i = li.SubItems.Count To lvwKetQua.Columns.Count - 1
                        li.SubItems.Add("")
                    Next
                    Dim index = lvwKetQua.Columns.IndexOf(lvwKetQua.Columns(td(0).InnerText))
                    li.SubItems(index).Text = td(6).InnerText.Trim()
                End If
            Next

            Exit For
        Next
        lblTrangThai.Text = "xong"
        li.EnsureVisible()
    End Sub

    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
        lvwKetQua.Items.Clear()
        While lvwKetQua.Columns.Count > 3
            lvwKetQua.Columns.RemoveAt(lvwKetQua.Columns.Count - 1)
        End While
    End Sub

    Private Sub btnLuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLuu.Click
        Dim Excel As Object = CreateObject("Excel.Application")
        Excel.ScreenUpdating = True
        Excel.Visible = False
        Dim xlWorkSheet As Object = Excel.Workbooks.Add
        For i = 0 To lvwKetQua.Columns.Count - 1
            Excel.Workbooks(1).Worksheets(1).Cells(1, i + 1).Value = lvwKetQua.Columns(i).Text
        Next
        For j = 0 To lvwKetQua.Items.Count - 1
            For i = 0 To lvwKetQua.Columns.Count - 1
                If i < lvwKetQua.Items(j).SubItems.Count Then
                    Excel.Workbooks(1).Worksheets(1).Cells(j + 2, i + 1).Value = lvwKetQua.Items(j).SubItems(i).Text
                End If
            Next
            lblTrangThai.Text = "Đang lưu (" & (j + 1) & "/" & lvwKetQua.Items.Count & ")"
        Next
        xlWorkSheet.SaveAs(Path.Combine(CurDir(), String.Format("{0}_{1}_{2}.xlsx", txtMaLop.Text, nudKy.Value, cbbNamHoc.SelectedItem)))
        Excel.Quit()
        Excel = Nothing
        MsgBox("Lưu bảng điểm hoàn tất !", MsgBoxStyle.Information)
        lblTrangThai.Text = "---"
    End Sub

    Private Sub lvwKetQua_ItemSelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ListViewItemSelectionChangedEventArgs) Handles lvwKetQua.ItemSelectionChanged
        lblDong.Text = e.ItemIndex + 1
    End Sub

    Private Sub llbAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles llbAbout.Click
        Process.Start("https://www.facebook.com/luong.xuan.manh")
    End Sub
End Class
